package com.promise.jokerdream.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp

/**
 * 时间选择对话框
 * 使用 PMDialog 承载 TimeInputField
 */
@Composable
fun TimePickerDialog(
    show: Boolean,
    onTimeSelected: (String) -> Unit,
    onDismiss: () -> Unit,
    description: String = "",
    selectedTime: String = "",
    minTime: String = "00:00",
    maxTime: String = "23:59",
    modifier: Modifier = Modifier
) {
    var currentTime by remember { mutableStateOf(selectedTime) }
    var isValid by remember { mutableStateOf(true) }
    var triggerValidation by remember { mutableStateOf(0) }

    // 状态重置函数
    fun resetState() {
        currentTime = selectedTime
        isValid = true
        triggerValidation = 0
    }
    
    // 每次显示时重置状态
    LaunchedEffect(show) {
        if (!show) {
            resetState()
        }
    }

    PMDialog(
        show = show,
        title = "选择挑战时间",
        confirmText = "确定",
        cancelText = "取消",
        onDismiss = onDismiss,
        onConfirm = {
            // 点击确认时进行校验
            triggerValidation++
            if (isValid) {
                onTimeSelected(currentTime)
            }
        }
    ) {
        Column {
            if (description.isNotEmpty()) {
                Text(
                    text = description,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(modifier = Modifier.height(8.dp))
            }
            
            TimeInputField(
                time = currentTime,
                onTimeChange = { currentTime = it },
                onValidationResult = { isValid = it },
                triggerValidation = triggerValidation,
                minTime = minTime,
                maxTime = maxTime,
                modifier = Modifier.fillMaxWidth()
            )
        }
    }
}
